package com.bac.rentmap.ad.flat.crawler;

import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Required;

import com.bac.rentmap.ad.flat.LocalAddress;
import com.bac.rentmap.ad.flat.crawler.localaddress.LocalAddressParser;

public class ParsingHelper {
    private static final Logger log = Logger.getLogger(ParsingHelper.class
            .getName());
    private LocalAddressParser simpleLocaAddressParser;
    private LocalAddressParser sentenceLocalAddressParser;

    private Pattern phonePattern = Pattern
            .compile("([\\d\\(][-\\d\\(\\) ]+[\\d\\)])");

    private Pattern roomPattern = Pattern
    .compile("(\\d+)(-комн| комн|-на ком|-х комн)");

    public void parseStreetAndBuilding(String address,
            FlatCrawledAd flatCrawledAd) {
        LocalAddress localAddress = simpleLocaAddressParser.parse(address);
        transformAddress(localAddress, flatCrawledAd);
    }

    public void parseStreetAndBuildingFromSentence(String address,
            FlatCrawledAd flatCrawledAd) {
        LocalAddress localAddress = sentenceLocalAddressParser.parse(address);
        transformAddress(localAddress, flatCrawledAd);
    }

    private void transformAddress(LocalAddress localAddress,
            FlatCrawledAd flatCrawledAd) {
        flatCrawledAd.setLocalAddress(localAddress);
    }

    public String parsePhone(String phoneString) {
        int commaPos = phoneString.indexOf(",");
        if (commaPos > 0) {
            phoneString = phoneString.substring(0, commaPos);
            log.fine("Detected multiple phones, parsing first one "
                    + phoneString);
        }
        Matcher matcher = phonePattern.matcher(phoneString);
        boolean matchFound = matcher.find();
        if (matchFound) {
            return matcher.group(0);
        }
        throw new IllegalArgumentException("Can't parse phone from "
                + phoneString);
    }

    public static String convertHtml2text(CharSequence htmlCharSequence) {
        if (htmlCharSequence == null)
            return null;
        String html = htmlCharSequence.toString();
        String res = html.replace("&nbsp;", " ");
        res = res.trim();
        if (res.isEmpty())
            return null;
        return res;
    }

    public void mayBeParseStreetAndBuilding(String header, String description,
            FlatCrawledAd flatCrawledAd) {
        if (flatCrawledAd.getStreet() == null
                || flatCrawledAd.getBuilding() == null) {
            try {
                log.fine("Parsing address from header");
                parseStreetAndBuildingFromSentence(header, flatCrawledAd);
            } catch (IllegalArgumentException e1) {
            }
        }
        if (description != null
                && (flatCrawledAd.getStreet() == null || flatCrawledAd
                        .getBuilding() == null)) {
            try {
                log.fine("Parsing address from description");
                parseStreetAndBuildingFromSentence(description, flatCrawledAd);
            } catch (IllegalArgumentException e1) {
            }
        }
        if (flatCrawledAd.getStreet() == null) {
            throw new IllegalArgumentException(
                    "Can't parse address from any places:\nheader: " + header
                            + "\ndescription: " + description);
        }
    }

    public Integer parsePrice(String priceString, Pattern pricePattern) {
        Matcher matcher = pricePattern.matcher(priceString);
        boolean matchFound = matcher.find();
        if (matchFound) {
            return new Integer(matcher.group(1));
        }
        throw new IllegalArgumentException("Can't parse price from "
                + priceString);
    }


    public String parseRoom(String header) {
        Matcher matcher = roomPattern.matcher(header);
        boolean matchFound = matcher.find();
        if (matchFound) {
            return matcher.group(1);
        }
        throw new IllegalArgumentException("Can't parse room from header "
                + header);
    }

    public String cleanPhone(String phoneString) {
        return phoneString.replaceAll("[- ()]", "");
    }

    @Required
    public void setSimpleLocaAddressParser(
            LocalAddressParser simpleLocaAddressParser) {
        this.simpleLocaAddressParser = simpleLocaAddressParser;
    }

    @Required
    public void setSentenceLocalAddressParser(
            LocalAddressParser sentenceLocalAddressParser) {
        this.sentenceLocalAddressParser = sentenceLocalAddressParser;
    }
}
